package ren.nearby.main.music;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;

import com.orhanobut.logger.Logger;

import java.util.List;

import am.widget.stateframelayout.StateFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.header.MaterialHeader;
import in.srain.cube.views.ptr.util.PtrLocalDisplay;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import ren.nearby.bean.beans.MusicBean;
import ren.nearby.lib.http.data.ResponseCallBack;
import ren.nearby.lib.ui.base.BaseActivity;
import ren.nearby.lib.ui.base.IPresenter;
import ren.nearby.main.R;
import ren.nearby.main.service.Music;
import ren.nearby.main.service.OnPlayerEventListener;
import ren.nearby.main.service.PlayService;

//import debug.MainApplication;
//import ren.nearby.main.login.DaggerLoginContractComponent;


/**
 * Created by Administrator on 2017/9/6 0006.
 */

public class MusicAct extends BaseActivity implements MusicContract.View, ResponseCallBack, OnPlayerEventListener {
    MusicAction action;
    Button btn_cache;
    PtrFrameLayout ptrFrameLayout;
    StateFrameLayout sf;

    //更新进度
    @Override
    public void onPublish(int progress) {

    }

    //切换歌曲
    @Override
    public void onChange(Music music) {
        ServiceUtils.getPlayService().playPause();
    }

    //暂停播放
    @Override
    public void onPlayerPause() {

    }

    //继续播放
    @Override
    public void onPlayerResume() {

    }

    //更新定时播放时间
    @Override
    public void onTimer(long remain) {

    }

    @Override
    public IPresenter getPresenter() {
        return action;
    }

    @Override
    public int getLayoutRes() {
        return R.layout.main_music;
    }

    private Drawable materialProgress;
    private Drawable mErrorDrawable;
    private Drawable mEmptyDrawable;


    @Override
    public void initView() {
        super.initView();
        toolBarBuilder
                .setIconLeft(R.mipmap.btn_back_white)
                .setBack(true)
                .setTitle(getResources().getString(R.string.main_login))
                .setBackgroundColor(R.color.colorPrimary)
                .setTitleColor(R.color.white)
                .build();
        //组件模式的初始化
/*        action = DaggerMusicContractComponent
                .builder()
                .appComponent(BaseApplication.getAppComponent())
                .actionModule(new ActionModule(this))
                .build().getAction();*/
        Logger.e(action == null ? "1" : "0");
//        action = DaggerMusicContractComponent.builder()
//                .actionModule(new ActionModule(this))
//                .tasksRepositoryComponent(MainApplication.getTasksRepositoryComponent())
//                .build()
//                .getAction();
        sf = (StateFrameLayout) findViewById(R.id.sf);
        materialProgress = ContextCompat.getDrawable(MusicAct.this, R.mipmap.ic_launcher);
        mErrorDrawable = ContextCompat.getDrawable(MusicAct.this, R.mipmap.ic_like);
        mEmptyDrawable = ContextCompat.getDrawable(MusicAct.this, R.mipmap.ic_empty);

        sf.setStateDrawables(materialProgress, mErrorDrawable, mEmptyDrawable);
        ptrFrameLayout = (PtrFrameLayout) findViewById(R.id.index_ptr_frame);
        //header
        final MaterialHeader header = new MaterialHeader(MusicAct.this);
        int[] headerColors = getResources().getIntArray(R.array.google_colors);
        header.setColorSchemeColors(headerColors);
        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
        header.setPadding(0, PtrLocalDisplay.dp2px(15), 0, PtrLocalDisplay.dp2px(10));
        header.setPtrFrameLayout(ptrFrameLayout);


        // footer
        final MaterialHeader footer = new MaterialHeader(MusicAct.this);
        int[] footerColors = getResources().getIntArray(R.array.google_colors);
        footer.setColorSchemeColors(footerColors);
        footer.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
        footer.setPadding(0, PtrLocalDisplay.dp2px(15), 0, PtrLocalDisplay.dp2px(10));
        footer.setPtrFrameLayout(ptrFrameLayout);

        ptrFrameLayout.setHeaderView(header);
        ptrFrameLayout.addPtrUIHandler(header);

        ptrFrameLayout.setFooterView(footer);
        ptrFrameLayout.addPtrUIHandler(footer);

        ptrFrameLayout.setPinContent(true);//原生状态
        ptrFrameLayout.setLoadingMinTime(1000);
        ptrFrameLayout.setDurationToCloseHeader(1500);
        ptrFrameLayout.setPtrHandler(new PtrDefaultHandler2() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {

                // TODO Auto-generated method stub
                Logger.e("下拉刷新");
                ptrFrameLayout.refreshComplete();

            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                // TODO Auto-generated method stub
                Logger.e("加载更多");
                ptrFrameLayout.refreshComplete();
            }

        });


        btn_cache = (Button) findViewById(R.id.main_btn_cache);
        btn_cache.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                setupWindowAnimations();
//                Intent intent = new Intent();
//                intent.setClass(LoginAct.this, NWelcome.class);
//                startActivity(intent);
                action.musicInterface(MusicAct.this);
            }
        });

        //启动服务
        startService();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                bindService();
            }
        }, 1000);


    }


    @Override
    protected void onResume() {
        super.onResume();
        Logger.e(" onResume ");


    }

    Handler handler = new Handler();

    public void startService() {
        Intent intent = new Intent(this, PlayService.class);
        startService(intent);
    }

    //扫码本地音乐
    private ServiceConnection mPlayServiceConnection;

    public void bindService() {
        Intent intent = new Intent();
        intent.setClass(this, PlayService.class);
        mPlayServiceConnection = new PlayServiceConnection();
        bindService(intent, mPlayServiceConnection, Context.BIND_AUTO_CREATE);
    }


    private class PlayServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            final PlayService playService = ((PlayService.PlayBinder) service).getService();
            Logger.e(playService != null ? " service not " : "service null");
            ServiceUtils.setPlayService(playService);
            Observable.create(new ObservableOnSubscribe<Integer>() {
                @Override
                public void subscribe(@NonNull ObservableEmitter<Integer> e) throws Exception {
                    playService.updateMusicList();
                    e.onNext(1);

                }
            }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<Integer>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            Logger.e("onSubscribe");

                        }

                        @Override
                        public void onNext(@NonNull Integer aVoid) {
                            Logger.e("onNext");
                            abcd();
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            Logger.e("onError" + e.getMessage());
                        }

                        @Override
                        public void onComplete() {
                            Logger.e("onComplete");
                        }
                    });

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    public void abcd() {
        Logger.e(" abcd ");
        if (ServiceUtils.getPlayService() != null) {
            ServiceUtils.getPlayService().setOnPlayerEventListener(this);
            onChange(ServiceUtils.getPlayService().getPlayingMusic());
        }
    }

    @Override
    public void onDataStart(int action) {
        Logger.e("onDataStart");
        sf.loading();
    }

    @Override
    public void onDataFailure(int from, String error) {
        Logger.e("onDataFailure");
        sf.error();
    }

    @Override
    public void onToast(String message) {
        Logger.e(" message = " + message);
    }

    @Override
    public void onDataSuccess(int from, Object results) {

        List<MusicBean> mbs = (List<MusicBean>) results;
        Logger.e("onDataSuccess" + mbs.size());


        sf.normal();
    }


    @Override
    public Context getContext() {
        return this;
    }


}
